package com.buobao.stream;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * stream的创建方式
 */
public class StreamGenerator {
    //基于数组创建
    @Test
    public void generatorl() {
        String[] arr = {"arr", "James", "Jack", "Function", "Naming"};
        Stream<String> stream = Stream.of(arr);
        stream.forEach(s -> System.out.println(s));
    }

    //基于集合创建
    @Test
    public void generator2() {
        List<String> list = new ArrayList<String>() {{
            add("arr");
            add("James");
            add("Jack");
        }};
        list.stream().forEach(s -> System.out.println(s));
    }

    //利用generate创建无限长度流
    @Test
    public void generator3() {
        Stream<Integer> stream = Stream.generate(() -> new Random().nextInt(100000));
        stream.limit(10).forEach(i -> System.out.println(i));
    }

    @Test
    public void generator4() {
        Stream<Integer> stream = Stream.iterate(1, n -> n + 10);
        stream.limit(10).forEach(i -> System.out.println(i));
    }

    @Test
    public void generator5() {
        String str = "abcdefg";
        IntStream stream = str.chars();
        stream.forEach(c -> System.out.println((char) c));
    }

    @Test
    public void coreFunctionShow() {
//        case1();
//        case2();
//        case3();
        case4();
    }

    /**
     * 输出所有偶数字符串
     */
    private void case1() {
        List<String> list = Arrays.asList("1", "2", "3", "4", "5");
        List<Integer> result = list.stream()
                .map((s) -> Integer.parseInt(s)) //转数字
                .filter(i -> i % 2 == 0)
                .collect(Collectors.toList());
        for (int i : result) {
            System.out.print(i + " ");
        }

        System.out.println(list.stream().mapToInt(s -> Integer.parseInt(s)).filter(i -> i % 2 == 0).sum());
    }

    private void case2() {
        List<String> names = Arrays.asList("jame","jack","tom","jackson");
        List<String> result =names.stream().map(s->s.substring(0,1).toUpperCase()+s.substring(1)).collect(Collectors.toList()); //在java16以后得版本中可以直接使用toList
        System.out.println(result);
    }

    //将所有奇数从大到小排列并去除重复项
    private void case3() {
        List<Integer> list = Arrays.asList(1,60,22,35,46,77,77,91,4,18);
        List<Integer> result = list.stream().filter(n->n%2==1).sorted((a,b)->b-a).distinct().collect(Collectors.toList());
        System.out.println(result);
    }

    private void case4() {
        String[][] arrays = {{"a", "b"}, {"c", "d", "e"}, {"f"}};
        List<String> flatList = Arrays.stream(arrays)
                .flatMap(Arrays::stream)
                .collect(Collectors.toList());
        System.out.println(flatList);
    }
}



















